﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using Janus.Windows.UI;
using VehicleScale.Models;
using VehicleScale.DataAccess;
using System.IO;
using Janus.Windows.GridEX.EditControls;
using System.Management;
using VehicleScale.Properties;
using System.Diagnostics;
using Janus.Windows.EditControls;

namespace VehicleScale
{
    public partial class FrmConfiguration : TemplateForm
    {

        #region Singleton Members
        private static volatile FrmConfiguration instance;
        private static object syncRoot = new Object();

        public static FrmConfiguration Instance
        {
            get
            {
                lock (syncRoot)
                {
                    if (instance == null)
                        instance = new FrmConfiguration();
                }

                return instance;
            }
        }
        #endregion

        #region Field Members

        private bool _isBinding = false;
        private readonly ParaPort _paraPort = new ParaPort();
        private readonly SettingApp _settings = new SettingApp();
        private readonly CompanyInfoModel _companyInfo = new CompanyInfoModel();
        private readonly ConfigModel _config = new ConfigModel();
        #endregion

        #region Properties
        private int TaskType
        {
            get
            {
                int result = 0;
                if (rdoOnce.Checked)
                    result = 1;
                else if (rdoDaily.Checked)
                    result = 2;
                else if (rdoWeekly.Checked)
                    result = 3;
                else if (rdoMonthly.Checked)
                    result = 4;
                return result;
            }
            set
            {
                switch (value)
                {
                    case 0:
                        rdoNone.Checked = true;
                        break;
                    case 1:
                        rdoOnce.Checked = true;
                        break;
                    case 2:
                        rdoDaily.Checked = true;
                        break;
                    case 3:
                        rdoWeekly.Checked = true;
                        break;
                    case 4:
                        rdoMonthly.Checked = true;
                        break;
                }
            }
        }
        #endregion

        #region Ctors
        public FrmConfiguration()
        {
            InitializeComponent();

            this.Size = new Common().SizeList;

            Initialize();
        }

        private void Initialize()
        {

            #region Main process (Load, OK, Cancel)
            this.MaximizeBox = false;

            this.Load += new EventHandler(delegate
            {

                LoadData();
                LoadPortControl();
                BindingControls();
                ValidatingControls();
                try
                {
                    LogFile.WriteLog(LogFile.nameFile, LogFile.userLogin, "Mo Form Cau hinh");
                }
                catch
                {
                }
            });

            this.btnOK.Click += new EventHandler(delegate { ClickButtonOK(); });
            this.btnCancel.Click += new EventHandler(delegate
            {
                this.Close();
            });
            #endregion

            #region Company Information
            this.btnBrowse.Click += new EventHandler(btnBrowse_Click);
            this.btnClear.Click += new EventHandler(btnClear_Click);
            #endregion

            #region Document Numbers
            this.btnResetImCode.Click += new EventHandler(btnResetCode_Click);
            this.btnResetExCode.Click += new EventHandler(btnResetCode_Click);
            #endregion

            #region Maintance
            this.btnBrowseLocation.Click += new EventHandler(btnBrowseLocation_Click);
            this.btnBackupNow.Click += new EventHandler(btnBackupNow_Click);
            this.btnRestore.Click += new EventHandler(btnRestore_Click);

            this.rdoNone.CheckedChanged += new EventHandler(delegate
                {
                    this.lblStartDate.Visible = false;
                    this.calendarStartDate.Visible = false;
                    this.lblStartTime.Visible = false;
                    this.calendarStartTime.Visible = false;
                    this.lblDaysOfWeek.Visible = false;
                    this.ucDaysOfWeek1.DaysOfWeek = 0;
                    this.ucDaysOfWeek1.Visible = false;
                    this.lblDaysOfMonth.Visible = false;
                    this.cboDaysOfMonth.SelectedIndex = -1;
                    this.cboDaysOfMonth.Visible = false;
                });

            this.rdoOnce.CheckedChanged += new EventHandler(delegate
            {
                this.lblStartDate.Visible = true;
                this.calendarStartDate.Visible = true;
                this.lblStartTime.Visible = true;
                this.calendarStartTime.Visible = true;
                this.lblDaysOfWeek.Visible = false;
                this.ucDaysOfWeek1.DaysOfWeek = 0;
                this.ucDaysOfWeek1.Visible = false;
                this.lblDaysOfMonth.Visible = false;
                this.cboDaysOfMonth.SelectedIndex = -1;
                this.cboDaysOfMonth.Visible = false;
            });

            this.rdoDaily.CheckedChanged += new EventHandler(delegate
            {
                this.lblStartDate.Visible = true;
                this.calendarStartDate.Visible = true;
                this.lblStartTime.Visible = true;
                this.calendarStartTime.Visible = true;
                this.lblDaysOfWeek.Visible = false;
                this.ucDaysOfWeek1.DaysOfWeek = 127;
                this.ucDaysOfWeek1.Visible = false;
                this.lblDaysOfMonth.Visible = false;
                this.cboDaysOfMonth.SelectedIndex = -1;
                this.cboDaysOfMonth.Visible = false;
            });

            this.rdoWeekly.CheckedChanged += new EventHandler(delegate
            {
                this.lblStartDate.Visible = true;
                this.calendarStartDate.Visible = true;
                this.lblStartTime.Visible = true;
                this.calendarStartTime.Visible = true;
                this.lblDaysOfWeek.Visible = true;
                this.ucDaysOfWeek1.DaysOfWeek = 0;
                this.ucDaysOfWeek1.Visible = true;
                this.lblDaysOfMonth.Visible = false;
                this.cboDaysOfMonth.SelectedIndex = -1;
                this.cboDaysOfMonth.Visible = false;
            });

            this.rdoMonthly.CheckedChanged += new EventHandler(delegate
            {
                this.lblStartDate.Visible = true;
                this.calendarStartDate.Visible = true;
                this.lblStartTime.Visible = true;
                this.calendarStartTime.Visible = true;
                this.lblDaysOfWeek.Visible = false;
                this.ucDaysOfWeek1.DaysOfWeek = 0;
                this.ucDaysOfWeek1.Visible = false;
                this.lblDaysOfMonth.Visible = true;
                this.cboDaysOfMonth.SelectedIndex = -1;
                this.cboDaysOfMonth.Visible = true;
            });
            #endregion

            #region Printer
            this.btnPrinterReceipt.Click += new EventHandler(delegate
            {
                PrintDialog printDialog1 = new PrintDialog();
                printDialog1.ShowDialog();
                txtPrinterReceipt.Text = printDialog1.PrinterSettings.PrinterName.ToString();
            });

            this.btnPrinterReport.Click += new EventHandler(delegate
            {
                PrintDialog printDialog1 = new PrintDialog();
                printDialog1.ShowDialog();
                txtPrinterReport.Text = printDialog1.PrinterSettings.PrinterName.ToString();
            });
            #endregion
        }

        #endregion

        #region Events

        #region Document Numbers
        void btnResetCode_Click(object sender, EventArgs e)
        {
            UIButton button = sender as UIButton;
            switch (button.Name)
            {
                case "btnResetImCode":
                    this.numImCodeStart.Value = 0;
                    _config.VehicleScaleImStart = 0;
                    break;
                case "btnResetExCode":
                    this.numExCodeStart.Value = 0;
                    _config.VehicleScaleExStart = 0;
                    break;
            }
        }
        #endregion

        #region Company Information
        void btnClear_Click(object sender, EventArgs e)
        {
            _companyInfo.LogoImage = null;
        }

        void btnBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "PNG Files (*.png;*.png)|*.png;*.png |JPEG (*.JPEG, *.JPG)|*.jpg;*.jpeg";
            openFileDialog.FilterIndex = 1;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                bool IsSaveImg = false;
                Image logoImage = Common.ScaleToSize(new Bitmap(openFileDialog.FileName), ref IsSaveImg);

                _companyInfo.LogoImage = logoImage;
                this.picLogoImage.BackgroundImage = logoImage;
            }
        }
        #endregion

        #region Maintance
        void btnBackupNow_Click(object sender, EventArgs e)
        {
            try
            {
                IConfigDataAccess dataAccess = new ConfigDataAccess();
                if (dataAccess.Backup(Common.Database, _settings.BackupLocation))
                    Library.Tools.MsgBox.Show("Sao lưu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                else
                    Library.Tools.MsgBox.Show("Sao lưu thất bại", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);

                #region OutPut
                //string outFileName = Common.outputPath;

                //string osql = String.Format("osql -E -q \"BACKUP DATABASE {1} TO DISK='{2}'\" -S \"{0}\" -o \"{3}\"",
                //            Common.Server, Common.Database, _settings.BackupLocation, outFileName);

                //string result = String.Empty;

                //using (Process proc = new Process())
                //{
                //    proc.StartInfo.FileName = @"osql";
                //    proc.StartInfo.Arguments = String.Format("-E -q \"BACKUP DATABASE {1} TO DISK='{2}'\" -S \"{0}\" -o \"{3}\"",
                //            Common.Server, Common.Database, _settings.BackupLocation, outFileName);
                //    proc.StartInfo.UseShellExecute = false;
                //    proc.StartInfo.RedirectStandardOutput = true;
                //    proc.StartInfo.RedirectStandardError = true;
                //    proc.StartInfo.CreateNoWindow = true;
                //    proc.Start();
                //    result = proc.StandardOutput.ReadToEnd();
                //    System.IO.File.AppendAllText(outFileName, result);
                //    proc.WaitForExit();
                //    result += proc.StandardOutput.ReadToEnd();
                //    System.IO.File.AppendAllText(outFileName, result);
                //    proc.Close();
                //}
                #endregion
            }
            catch (Exception ex)
            {
                Library.Tools.MsgBox.Show("Quá trình sao lưu thất bại. Chi tiết lỗi: " + ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
        }

        void btnRestore_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Filter = "Backup Files (*.bak;*.backup)|*.bak;*.backup |Vehicle Scale Files (*.vsf)|*.vsf";
                openFileDialog.FilterIndex = 1;
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    string filename = openFileDialog.FileName;

                    IConfigDataAccess dataAccess = new ConfigDataAccess();
                    if (dataAccess.Backup(Common.Database, filename))
                        Library.Tools.MsgBox.Show("Phục hồi thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    else
                        Library.Tools.MsgBox.Show("Phục hồi thất bại", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    #region Output
                    string outFileName = Common.outputPath;

                    string osql = String.Format("osql  -U \"{3}\" -P \"{4}\" -q \"RESTORE DATABASE {1} FROM DISK='{2}' WITH  FILE = 1, NOUNLOAD, STATS = 10\" -S \"{0}\"",
                                Common.Server, Common.Database, filename, Common.UserRestore, Common.PasswordRestore);
                    string result = String.Empty;

                    using (Process proc = new Process())
                    {
                        proc.StartInfo.FileName = @"osql";
                        proc.StartInfo.Arguments = String.Format(" -U \"{3}\" -P \"{4}\" -q \"RESTORE DATABASE {1} FROM DISK='{2}' WITH  FILE = 1, NOUNLOAD\" -S \"{0}\"",
                                Common.Server, Common.Database, filename, Common.UserRestore, Common.PasswordRestore);
                        proc.StartInfo.UseShellExecute = false;
                        proc.StartInfo.RedirectStandardOutput = true;
                        proc.StartInfo.RedirectStandardError = true;
                        proc.StartInfo.CreateNoWindow = true;
                        proc.Start();
                        result = proc.StandardOutput.ReadToEnd();
                        System.IO.File.AppendAllText(outFileName, result);
                        proc.WaitForExit();
                        result += proc.StandardOutput.ReadToEnd();
                        System.IO.File.AppendAllText(outFileName, result);
                    }
                    #endregion

                }
            }
            catch (Exception ex)
            {
                Library.Tools.MsgBox.Show("Quá trình sao lưu thất bại. Chi tiết lỗi: " + ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
        }

        void btnBrowseLocation_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Backup Files (*.bak;*.backup)|*.bak;*.backup |Vehicle Scale Files (*.vsf)|*.vsf";
            saveFileDialog.FilterIndex = 1;
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                this.edtBackupLocation.Text = saveFileDialog.FileName;
            }
        }
        #endregion

        #endregion

        #region Methods

        private void ValidatingControls()
        {
            //this.edtOldPassword.Validating += new CancelEventHandler(delegate
            //{
            //    if (String.IsNullOrEmpty(this.edtOldPassword.Text))
            //    {
            //        errorProvider.SetError(this.edtOldPassword, "Bạn phải nhập mật khẩu cũ.");
            //    }
            //    else if (Library.Encrypt.Encrypt.Encode("MD5", this.edtOldPassword.Text) != Common.UserLogin.Password)
            //    {
            //        errorProvider.SetError(this.edtOldPassword, "Bạn nhập sai mật khẩu cũ.");
            //    }
            //    else
            //    {
            //        errorProvider.SetError(this.edtOldPassword, String.Empty);
            //    }
            //});

            //this.edtNewPassword.Validating += new CancelEventHandler(delegate
            //{
            //    if (String.IsNullOrEmpty(this.edtNewPassword.Text))
            //    {
            //        errorProvider.SetError(this.edtNewPassword, "Bạn phải nhập mật khẩu mới.");
            //    }
            //    else if (this.edtNewPassword.TextLength < 6 || this.edtNewPassword.Text == this.edtOldPassword.Text)
            //    {
            //        errorProvider.SetError(this.edtNewPassword, "Mật khẩu phải có chiều dài ít nhất 6 ký tự.\nVà phải khác với mật khẩu cũ");
            //    }
            //    else
            //    {
            //        errorProvider.SetError(this.edtNewPassword, String.Empty);
            //    }
            //});

            //this.edtConfirmPassword.Validating += new CancelEventHandler(delegate
            //{
            //    if (this.edtNewPassword.Text != this.edtConfirmPassword.Text)
            //    {
            //        errorProvider.SetError(this.edtConfirmPassword, "Mật khẩu nhập lại phải giống mật khẩu mới.");
            //    }
            //    else
            //    {
            //        errorProvider.SetError(this.edtConfirmPassword, String.Empty);
            //    }
            //});

        }
        private void ResetBindingControls()
        {
            this.cboPortName.DataBindings.Clear();
            this.cboBaudRate.DataBindings.Clear();
            this.cboParity.DataBindings.Clear();
            this.cboDataBits.DataBindings.Clear();
            this._isBinding = false;
        }
        private void BindingControls()
        {
            if (!_isBinding)
            {
                // Binding company info.
                this.picLogoImage.DataBindings.Add("BackgroundImage", _companyInfo, "LogoImage");
                this.edtCompanyName.DataBindings.Add("Text", _companyInfo, "CompanyName");
                this.edtAddress.DataBindings.Add("Text", _companyInfo, "Address");
                this.edtTelephone.DataBindings.Add("Text", _companyInfo, "Telephone");
                this.edtFaxNumber.DataBindings.Add("Text", _companyInfo, "FaxNumber");
                this.edtTaxCode.DataBindings.Add("Text", _companyInfo, "TaxCode");

                this.maskEmployeePrefix.DataBindings.Add("Text", _config, "EmployeePrefix");
                this.maskCustomerPrefix.DataBindings.Add("Text", _config, "CustomerPrefix");
                this.maskCategoryPrefix.DataBindings.Add("Text", _config, "CategoryPrefix");
                this.maskProductPrefix.DataBindings.Add("Text", _config, "ProductPrefix");
                this.maskVehicleScaleImPrefix.DataBindings.Add("Text", _config, "VehicleScaleImPrefix");
                this.maskVehicleScaleExPrefix.DataBindings.Add("Text", _config, "VehicleScaleExPrefix");
                this.edtEmployeeCodeLength.DataBindings.Add("Text", _config, "EmployeeCode");
                this.edtCustomerCodeLength.DataBindings.Add("Text", _config, "CustomerCode");
                this.edtCategoryCodeLength.DataBindings.Add("Text", _config, "CategoryCode");
                this.edtProductCodeLength.DataBindings.Add("Text", _config, "ProductCode");
                this.edtVehicleScaleImLength.DataBindings.Add("Text", _config, "VehicleScaleImCode");
                this.edtVehicleScaleExLength.DataBindings.Add("Text", _config, "VehicleScaleExCode");
                this.numImCodeStart.DataBindings.Add("Value", _config, "VehicleScaleImStart");
                this.numExCodeStart.DataBindings.Add("Value", _config, "VehicleScaleExStart");

                // Config devices.
                this.cboPortName.DataBindings.Add("SelectedValue", _paraPort, "PortName");
                this.cboBaudRate.DataBindings.Add("SelectedValue", _paraPort, "BaudRate");
                this.cboParity.DataBindings.Add("SelectedIndex", _paraPort, "Parity");
                this.cboDataBits.DataBindings.Add("SelectedValue", _paraPort, "DataBits");

                // GUI
                this.colorBackground.DataBindings.Add("SelectedColor", _settings, "BackColor");
                this.cboStyle.DataBindings.Add("SelectedValue", _settings, "Style");
                this.colorCustomColor.DataBindings.Add("SelectedColor", _settings, "CustomColor");
                this.cboColorScheme.DataBindings.Add("SelectedValue", _settings, "ColorScheme");

                // Maintance
                this.edtBackupLocation.DataBindings.Add("Text", _settings, "BackupLocation", true, DataSourceUpdateMode.OnPropertyChanged);
                this.calendarStartDate.DataBindings.Add("Value", _settings, "StartDate");
                this.calendarStartTime.DataBindings.Add("Value", _settings, "StartTime");
                this.ucDaysOfWeek1.DataBindings.Add("DaysOfWeek", _settings, "DaysOfWeek");
                this.cboDaysOfMonth.DataBindings.Add("SelectedValue", _settings, "DaysOfMonth");

                // Printer
                this.txtPrinterReceipt.DataBindings.Add("Text", _settings, "ReceiptPrintName", true, DataSourceUpdateMode.OnPropertyChanged);
                this.txtPrinterReport.DataBindings.Add("Text", _settings, "ReportPrintName", true, DataSourceUpdateMode.OnPropertyChanged);
                this.chkPreviewReceipt.DataBindings.Add("Checked", _settings, "IsPreviewReceiptPrint");
                this.chkPreviewReport.DataBindings.Add("Checked", _settings, "IsPreviewReportPrint");

                _isBinding = true;
            }
        }
        private void LoadPortControl()
        {
            // Ports.
            foreach (var str in SerialPort.GetPortNames())
            {
                this.cboPortName.Items.Add(str);
            }

            // Parity.
            foreach (string str in Enum.GetNames(typeof(Parity)))
            {
                cboParity.Items.Add(str);
            }
        }
        private void LoadData()
        {
            // Load Company Info
            if (Common.CompanyInfo != null) Common.CompanyInfo.CopyTo<CompanyInfoModel>(_companyInfo);

            // Load Config
            if (Common.Config != null) Common.Config.CopyTo<ConfigModel>(_config);
            this.TaskType = _settings.TaskType;

            // Load days of month
            this.cboDaysOfMonth.Items.Clear();
            string suffix = String.Empty;
            for (uint i = 1; i < 32; i++)
            {
                if (i % 10 == 1 && i != 11)
                    suffix = "st";
                else if (i % 10 == 2 && i != 12)
                    suffix = "nd";
                else if (i % 10 == 3 && i != 13)
                    suffix = "rd";
                else
                    suffix = "th";

                this.cboDaysOfMonth.Items.Add(new Janus.Windows.EditControls.UIComboBoxItem(String.Format("{0}{1}", i, suffix), (i - 1) ^ 2));
            }

            // Load style.
            this.cboStyle.Items.Clear();
            this.cboStyle.Items.Add(VisualStyle.Default);
            this.cboStyle.Items.Add(VisualStyle.Office2003);
            this.cboStyle.Items.Add(VisualStyle.Office2007);
            this.cboStyle.Items.Add(VisualStyle.OfficeXP);
            this.cboStyle.Items.Add(VisualStyle.Standard);
            this.cboStyle.Items.Add(VisualStyle.VS2005);

            // Load colorScheme.
            this.cboColorScheme.Items.Clear();
            this.cboColorScheme.Items.Add(Janus.Windows.Ribbon.Office2007ColorScheme.Default);
            this.cboColorScheme.Items.Add(Janus.Windows.Ribbon.Office2007ColorScheme.Black);
            this.cboColorScheme.Items.Add(Janus.Windows.Ribbon.Office2007ColorScheme.Blue);
            this.cboColorScheme.Items.Add(Janus.Windows.Ribbon.Office2007ColorScheme.Silver);
            this.cboColorScheme.Items.Add(Janus.Windows.Ribbon.Office2007ColorScheme.Custom);

        }
        private bool CreateBackupTaskSchedule()
        {
            uint ret = 0;
            string LocalDateTime = ScheduleJob.ToDMTFTime(new DateTime(
                        _settings.StartDate.Year,
                        _settings.StartDate.Month,
                        _settings.StartDate.Day,
                        _settings.StartTime.Hour,
                        _settings.StartTime.Minute,
                        _settings.StartDate.Second)); // convert to DMTF format
            string osql = String.Format("osql -E -q \"BACKUP DATABASE {1} TO DISK='{2}'\" -S \"{0}\"",
                        Common.Server, Common.Database, _settings.BackupLocation);
            uint jobID = 0;

            switch (TaskType)
            {
                case 0:
                    if (_settings.JobID > 0) ret = ScheduleJob.Delete(_settings.JobID);
                    break;
                case 1:
                    ret = ScheduleJob.Create(osql, 0, 0, true, true, LocalDateTime, out jobID);
                    break;
                case 2:
                    ret = ScheduleJob.Create(osql, _settings.DaysOfWeek, 0, true, true, LocalDateTime, out jobID);
                    break;
                case 3:
                    ret = ScheduleJob.Create(osql, _settings.DaysOfWeek, 0, true, true, LocalDateTime, out jobID);
                    break;
                case 4:
                    ret = ScheduleJob.Create(osql, 0, _settings.DaysOfMonth, true, true, LocalDateTime, out jobID);
                    break;
            }

            _settings.JobID = jobID;
            return ret == 0;
        }

        #endregion

        #region Action Members

        /// <summary>
        /// Click button OK
        /// </summary>
        private void ClickButtonOK()
        {
            _settings.TaskType = TaskType;
            if (CreateBackupTaskSchedule())
            {
                ICompanyInfoDataAccess dataAccess = new CompanyInfoDataAccess();
                if (Common.CompanyInfo == null)
                {
                    if (dataAccess.Add(_companyInfo))
                    {
                        Common.CompanyInfo = new CompanyInfoModel();
                        _companyInfo.CopyTo<CompanyInfoModel>(Common.CompanyInfo);
                    }
                }
                else
                {
                    if (dataAccess.Edit(_companyInfo))
                    {
                        _companyInfo.CopyTo<CompanyInfoModel>(Common.CompanyInfo);
                    }
                }

                IConfigDataAccess configDA = new ConfigDataAccess();
                if (Common.Config == null)
                {
                    if (configDA.Add(_config))
                    {
                        Common.Config = new ConfigModel();
                        _config.CopyTo<ConfigModel>(Common.Config);
                    }
                }
                else
                {
                    if (configDA.Edit(_config))
                    {
                        _config.CopyTo<ConfigModel>(Common.Config);
                    }
                }

                Settings.Default.Save();
                Library.Tools.MsgBox.Show("Lưu cấu hình thành công!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                try
                {
                    LogFile.WriteLog(LogFile.nameFile, LogFile.userLogin, "Thay doi Cau hinh");
                }
                catch
                {
                }
            }
            else
            {
                Library.Tools.MsgBox.Show("Lưu cấu hình thất bại => ERROR!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        protected override void OnClosed(EventArgs e)
        {
            instance = null;
            Settings.Default.Reload();
            base.OnClosed(e);
        }
        #endregion

    }

    #region Schedule Job Class
    class ScheduleJob
    {
        public static uint Create(string Command, uint DaysOfMonth, uint DaysOfWeek,
                bool InteractWithDesktop, bool RunRepeatedly, string StartTime, // in DMTF format !
                out uint JobId)
        {
            // See: Platform SDK (or WMI SDK) doc's for detailed info about 'Win32_ScheduledJob' class
            ManagementBaseObject inputArgs = null;
            ManagementClass classObj = new ManagementClass(null, "Win32_ScheduledJob", null);
            inputArgs = classObj.GetMethodParameters("Create");
            inputArgs["Command"] = Command;
            inputArgs["DaysOfMonth"] = DaysOfMonth;
            inputArgs["DaysOfWeek"] = DaysOfWeek;
            inputArgs["InteractWithDesktop"] = InteractWithDesktop;
            inputArgs["RunRepeatedly"] = RunRepeatedly;
            inputArgs["StartTime"] = StartTime;
            // use late binding to invoke "Create" method on "Win32_ScheduledJob" WMI class
            ManagementBaseObject outParams = classObj.InvokeMethod("Create", inputArgs, null);
            JobId = ((uint)(outParams.Properties["JobId"].Value));
            return ((uint)(outParams.Properties["ReturnValue"].Value));
        }
        // Delete the Scheduled (JobID)

        public static uint Delete(uint JobID)
        {
            ManagementObject mo;
            ManagementPath path = ManagementPath.DefaultPath;
            path.RelativePath = "Win32_ScheduledJob.JobId=" + "\"" + JobID + "\"";
            mo = new ManagementObject(path);
            ManagementBaseObject inParams = null;
            // use late binding to invoke "Delete" method on "Win32_ScheduledJob" WMI class
            ManagementBaseObject outParams = mo.InvokeMethod("Delete", inParams, null);
            return ((uint)(outParams.Properties["ReturnValue"].Value));
        }

        public static string ToDMTFTime(DateTime dateParam)
        {
            string tempString = dateParam.ToString("********HHmmss.ffffff");
            TimeSpan tickOffset = TimeZone.CurrentTimeZone.GetUtcOffset(dateParam);
            tempString += (tickOffset.Ticks >= 0) ? '+' : '-';
            tempString += (Math.Abs(tickOffset.Ticks) / System.TimeSpan.TicksPerMinute).ToString("d3");
            return tempString;
        }
    }
    #endregion

}
